/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_kit/zhiqim_git.htm
 *
 * ZhiqimGit is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.git.command;

import org.zhiqim.git.Git;
import org.zhiqim.git.GitCommand;
import org.zhiqim.git.refer.Ref;
import org.zhiqim.git.refer.RefRenamer;
import org.zhiqim.git.refer.RefUpdateResult;
import org.zhiqim.git.util.GitValidates;

import org.zhiqim.kernel.util.Asserts;

/**
 * 分枝重命名命令
 * http://www.kernel.org/pub/software/scm/git/docs/git-branch.html
 *
 * @version v1.0.0 @author zhichenggang 2017-3-12 新建与整理
 */
public class BranchRenameCommand extends GitCommand<Ref>
{
    private String oldName;
    private String newName;
    
    public BranchRenameCommand(Git git)
    {
        super(git);
    }

    /******************************************************************************/
    //设置参数
    /******************************************************************************/
    
    public BranchRenameCommand setNewName(String newName)
    {
        this.newName = newName;
        return this;
    }

    public BranchRenameCommand setOldName(String oldName)
    {
        this.oldName = oldName;
        return this;
    }

    protected void preprocess()
    {
        Asserts.assertNotEmptyBlank(oldName, "原分枝名称不能为空");
        Asserts.asserts(!MASTER.equals(oldName), "主分枝名称不能重命名");
        Asserts.asserts(git.hasRef(P_REFS_HEADS_ + oldName), "原分枝不存在");
        Asserts.asserts(GitValidates.isValidRefName(P_REFS_HEADS_ + newName), "新分枝名称不合法");
    }
    
    @Override
    protected Ref execute() throws Exception
    {
        //1.重命名到分枝引用文件和引用日志文件
        RefRenamer renamer = git.newRenamer(P_REFS_HEADS_ + oldName, P_REFS_HEADS_ + newName);
        RefUpdateResult result = renamer.rename();
        if (result != RefUpdateResult.RENAMED)
            throw Asserts.exception("重命名分枝[%s]到[%s]时失败，结果：[%s]", oldName, newName, result);
        
        //2.重命名分枝配置文件
        git.getConfig().updateBranch(oldName, newName);
        git.getConfig().save();
        
        return git.scanRef(P_REFS_HEADS_ + newName);
    }
}
